var room_id=1;
var default_av="http://tva3.sinaimg.cn/crop.376.43.581.581.50/7affb2a5jw8exep574138j20xc0l5452.jpg";
var ws = {};
var userlist = {}; 
var userinfo = {}
var reply_uid=null;
var reply_message=null;
var reply_time=null;
var reply_name=null;


	//使用原生WebSocket
/*	if (window.WebSocket || window.MozWebSocket)
	{
		ws = new WebSocket(webim.server);
	}
	//使用flash websocket
	else if (webim.flash_websocket)
	{
		WEB_SOCKET_SWF_LOCATION = "/static/flash-websocket/WebSocketMain.swf";
		$.getScript("/static/flash-websocket/swfobject.js", function () {
			$.getScript("/static/flash-websocket/web_socket.js", function () {
				ws = new WebSocket(webim.server);
			});
		});
	}
	//使用http xhr长轮循
	else
	{
		ws = new Comet(webim.server);
	}*/
	//listenEvent();


function listenEvent() {
	/**
	 * 连接建立时触发
	 */
	//使用原生WebSocket
	if (window.WebSocket || window.MozWebSocket)
	{
		ws = new WebSocket(webim.server);
	}
	//使用flash websocket
	else if (webim.flash_websocket)
	{
		WEB_SOCKET_SWF_LOCATION = "/static/flash-websocket/WebSocketMain.swf";
		$.getScript("/static/flash-websocket/swfobject.js", function () {
			$.getScript("/static/flash-websocket/web_socket.js", function () {
				ws = new WebSocket(webim.server);
			});
		});
	}
	//使用http xhr长轮循
	else
	{
		ws = new Comet(webim.server);
	}
	ws.onopen = function (e) {
		//发送登录信息
		msg = new Object();
		msg.cmd = 'login';
		msg.name = userinfo.user.user_nicename || "未设置";
		msg.avatar = userinfo.user.avatar || default_av
		msg.fd = userinfo.user.id;
		msg.uid = userinfo.user.id;
		ws.send($.toJSON(msg));
	};

	//有消息到来时触发
	ws.onmessage = function (e) {
		var message = $.evalJSON(e.data);
		var cmd = message.cmd;
		//console.log(message)
		if (cmd == 'login')
		{
			//client_id = $.evalJSON(e.data).fd;
			//获取在线列表
			//ws.send($.toJSON({cmd: 'getOnline'}));
			//获取历史记录
			//ws.send($.toJSON({cmd: 'getHistory'}));
			//alert( "收到消息了:"+e.data );
		}
		else if (cmd == 'call')
		{
			$("#callDataBox").html(Handlebars.compile($("#callTemplate").html())(message))

		}
		else if(cmd == 'note'){
			showNewNote(message)
		}
		else if (cmd == 'fromMsg')
		{
			if(message.user){
				var usertype = message.user.is_teacher ? "teacher" : "user"	
			}
			else{
				var usertype = "user";
			}
			showNewMsg(message,usertype);

		}
		else if (cmd == 'live')
		{
			statusClass(message.status);
		}
	};

	/**
	 * 连接关闭事件
	 */
	ws.onclose = function (e) {
        msg = new Object();
        msg.cmd = 'close';
        msg.name = userinfo.user.user_nicename;
        msg.room = room_id;
        msg.avatar = userinfo.user.avatar;
        ws.send($.toJSON(msg));
		setTimeout(function () {
			console.log("对不起，聊天服务器特殊原因中断，请再次刷新！")
		}, 1000)
		listenEvent();
	};

	/**
	 * 异常事件
	 */
	ws.onerror = function (e) {
		//alert("异常:" + e.data);
	};
}



/*消息历史翻页*/
function historyPage(dataObj,type) {
    if(dataObj){	
		for (var i =0 ; i <dataObj.length; i++) {
				showNewMsg(dataObj[i],type,"page");
					
		}
		if(type=="teacher"){
			var ul_module = $('#chat-teacher-messages');
			var seleted_li = $('.teacherMsg').slice(0, dataObj.length);
		}
		else{
			var ul_module = $('#chat-messages');
			var seleted_li = $('.message-container').slice(0, dataObj.length);
		}
		
		var ul_height = ul_module.height();
		var height = 0;
		$.each(seleted_li,function(i){
			height +=$(this).height();
		})
	    ul_module.scrollTop(height+26*dataObj.length);
    }
}
/*纸条历史翻页*/
function noteHistoryPage(dataObj) {
    if(dataObj){	
		for (var i =0 ; i <dataObj.length; i++) {
				showNewNote(dataObj[i],"page");
					
		}
		var ul_module = $('#note-msg');
		var seleted_li = $('.noteMsg').slice(0, dataObj.length);
		var ul_height = ul_module.height();
		var height = 0;
		$.each(seleted_li,function(i){
			height +=$(this).height();
		})
	    ul_module.scrollTop(height+26*dataObj.length);
    }
}
/**
 * 显示用户消息
 */

function showNewMsg(dataObj,user_type,type) {
	
    //console.log(dataObj)
    if(user_type=="teacher"){
    	var dom =Handlebars.compile($("#teacherChatTemplate").html())(dataObj)
	    if(type){
	    	$("#chat-teacher-messages").prepend(dom)
	    }
	    else{
	    	$("#chat-teacher-messages").append(dom)
		    $('#chat-teacher-messages')[0].scrollTop = 1000000;
	    }
    }
    else{
    	var dom =Handlebars.compile($("#userChatTemplate").html())(dataObj)
    	if(type){
    		$("#chat-messages").prepend(dom)
	    }
	    else{
	    	$("#chat-messages").append(dom)
		    $('#chat-messages')[0].scrollTop = 1000000;
	    }
    }
    changeFace() 
}
/*纸条消息*/
function showNewNote(dataObj,type) {
	
    //console.log(dataObj)
    	var dom =Handlebars.compile($("#userNoteTemplate").html())(dataObj)
    	if(type){
    		$("#note-msg").prepend(dom)
	    }
	    else{
	    	$("#note-msg").append(dom)
		    $('#note-msg')[0].scrollTop = 1000000;
	    }
     changeFace()
}
function changeFace(){
	//替换表情
    $(".chatcontent").each(function(){
    	$(this).html(parseXss($(this).html()))
    }) 
}
function xssFilter(val) {
	val = val.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\x22/g, '&quot;').replace(/\x27/g, '&#39;');
	return val;
}

function parseXss(val) {
	val = val.replace(/#(\d*)/g, '<img src="public/static/img/face/$1.gif" />');
	val = val.replace('&amp;', '&');
	return val;
}



/**
 * 上课
 * @return {[type]} [description]
 */
function statusClass(status) {
	if(status==1){
			$(".stopLive").fadeOut();
			$(".oc-live").hide();
			$(".close-live").show();
		
	}
	else if(status==-1){
			$(".stopLive").html('<img src="public/static/img/live-status.jpg">').show();
			$(".oc-live").hide();
			$(".open-live").show();
		
	}
	
}


function selectUser(userid) {
	$('#userlist').val(userid);
}

function delUser(userid) {
	$('#user_' + userid).remove();
	$('#inroom_' + userid).remove();
	delete (userlist[userid]);
}

function sendMsg(content, type,usertype) {
	var usertype = usertype ? usertype : "";
	var now=new Date();
	var msg = {};
	if (!content) {
		return false;
	}
	//content.substring(0, content.indexOf('|]'))
	if(content.indexOf('|]')>0){
		content = content.replace(content.substring(0, content.indexOf('|]')+2),"");
	}
	msg.cmd = 'message';
	msg.from = userinfo.user.id;
	msg.data = content;
	msg.type = type;
	msg.create_time = now;
	msg.reply_uid=reply_uid;
	msg.reply_message=reply_message;
	msg.reply_time=reply_time;
	msg.reply_name =reply_name;
	msg.reply_user={
		avatar:null,
		name:reply_name
	}
	if(usertype=="teacher"){
		msg.size=$(".chat_fontsize").val();
		msg.color=$(".chat_fontcolor").val();
	}
	ws.send($.toJSON(msg));
	msg.user={
		avatar:userinfo.user.avatar||"/public/static/img/dftx.jpg",
		name:userinfo.user.user_nicename,
		isme:true,
		uid:userinfo.user.id
	};
	showNewMsg(msg,usertype);
	reply_uid=null;
	reply_message=null;
	reply_time=null;
	reply_name=null
	$('#msg_content').val('');
}
/*发送纸条*/
function sendNote(content, type,usertype) {
	var usertype = usertype ? usertype : "";
	var now=new Date();
	var msg = {};
	if (!content) {
		return false;
	}
	//content.substring(0, content.indexOf('|]'))
	if(content.indexOf('|]')>0){
		content = content.replace(content.substring(0, content.indexOf('|]')+2),"");
	}

	msg.cmd = 'note';
	msg.from = userinfo.user.id;
	msg.to = $("#teacherSelect").val() || reply_uid;
	msg.data = content;
	msg.type = type;
	msg.create_time = now;
	msg.note_uid= usertype=="teacher" ? reply_uid :null;
	msg.note_message= usertype=="teacher" ? reply_message : "";
	msg.note_time= usertype=="teacher"? reply_time : "";
	msg.user={
		avatar:userinfo.user.avatar||"/public/static/img/dftx.jpg",
		name:userinfo.user.user_nicename,
		isme:true,
		uid:userinfo.user.id
	}
	msg.to_user={
		avatar:"",
		name:$("#teacherSelect option:selected").html() || reply_name,
		uid:$("#teacherSelect").val() || reply_uid
	}
	ws.send($.toJSON(msg));
	showNewNote(msg);
	reply_uid=null;
	reply_message=null;
	reply_time=null;
	reply_name=null
	$('#note_content').val('');
}


$(document).ready(function () {
	var a = '';
	for (var i = 1; i < 22; i++) {
		a = a + '<a class="face" href="#" onclick="selectFace(this,' + i + ');return false;"><img src="public/static/img/face/' + i + '.gif" /></a>';
	}
	$(".show_face").html(a+'<div class="close_face"></div>');
	$(".close_face").click(function(){
		$(".show_face").removeClass("show_face_hovers")
	})
});
/*选择表情*/
function selectFace(obj,id) {
	var img = '<img src="public/static/img/face/' + id + '.gif" />';
	$(obj).parent().parent().find(".areacontent").insertAtCaret("#" + id);
	toggleFace($(obj).parent().attr("id"))
}
/*显示表情库*/

function toggleFace(obj) {

	$("#"+obj).toggleClass("show_face_hovers");
}

function toTalk(val){
	if(val){
		var t=val;
		if(t!=0){
			reply_uid=$(t).attr("data-uid");
			reply_message=$(t).attr("data-content");
			reply_time=$(t).attr("data-time");
			reply_name=$(t).attr("data-uname");
			$("#msg_content").val("[|@"+$(t).attr("data-uname")+" "+$(t).attr("data-content")+"|]").focus()
		}
	}	
}
function toNote(val){
	if(val){
		var t=val;
		if(t!=0){
			reply_uid=$(t).attr("data-uid");
			reply_message=$(t).attr("data-content");
			reply_time=$(t).attr("data-time");
			reply_name=$(t).attr("data-uname");
			$("#note_content").val("[|@"+$(t).attr("data-uname")+" "+$(t).attr("data-content")+"|]").removeAttr("disabled")
		}
	}	
}
//问答
function askSend(){
	var url = webconfig.apihost+"?c=api&a=addmessage&callback=?";
	var content = $(".askcontent").val();
	if(content==""){
		alert("请输入问题");
		return;
	}
    $.getJSON(url,{"room_id":room_id,"content":content},function(response){
        if(response.code==1){
            alert("提交成功");
            $(".askcontent").val("");
        }
        else{
        	alert(response.message)
        }
        
    })
}

//var dirtyWord = noword.split("|");
function filterWord(messageValue) {
	var messageValue_new = messageValue;
	for (var i = 0; i < dirtyWord.length; i++) {
		messageValue_new = filterOneWord(messageValue_new, dirtyWord[i]); //过滤单个词语并返回过滤后的内容
	}
	return messageValue_new;
}
function filterOneWord(messageValue, oneDirtyWord) {
	var messageValue_new = messageValue;
	var x = "";
	for (var i = 0; i < oneDirtyWord.length; i++) {
		x += "*"
	}
	messageValue_new = messageValue_new.replace(oneDirtyWord, x);
	return messageValue_new;
}
(function ($) {
	$.fn.extend({
		insertAtCaret: function (myValue) {
			var $t = $(this)[0];
			if (document.selection) {
				this.focus();
				sel = document.selection.createRange();
				sel.text = myValue;
				this.focus();
			}
			else if ($t.selectionStart || $t.selectionStart == '0') {

				var startPos = $t.selectionStart;
				var endPos = $t.selectionEnd;
				var scrollTop = $t.scrollTop;
				$t.value = $t.value.substring(0, startPos) + myValue + $t.value.substring(endPos, $t.value.length);
				this.focus();
				$t.selectionStart = startPos + myValue.length;
				$t.selectionEnd = startPos + myValue.length;
				$t.scrollTop = scrollTop;
			}
			else {

				this.value += myValue;
				this.focus();
			}
		}
	})
})(jQuery);
$(document).ready(function(){
$(".contab").click(function(){
    $(".contab").removeClass('active');
    $(this).addClass("active");
    $(".pailistbox").hide();
    $(".pailistbox").eq($(this).index()).show(); 
})
$("#chat-teacher-messages").scroll(function(){
　　var scrollTop = $(this).scrollTop();
　　if(scrollTop == 0){
　　　　var p = ($("#chat-teacher-messages").attr("data-page"))*1+1;
        loadHistoryMes(2,p,20);
        $("#chat-teacher-messages").attr("data-page",p)
　　}
});
$("#chat-messages").scroll(function(){
　　var scrollTop = $(this).scrollTop();
　　if(scrollTop == 0){
　　　　var p = ($("#chat-messages").attr("data-page"))*1+1;
        loadHistoryMes(3,p,20);
        $("#chat-messages").attr("data-page",p)
　　}
});
$("#note-msg").scroll(function(){
　　var scrollTop = $(this).scrollTop();
　　if(scrollTop == 0){
　　　　var p = ($("#note-msg").attr("data-page"))*1+1;
        loadHistoryNote(p,20);
        $("#note-msg").attr("data-page",p)
　　}
});
$("#zf-boxdiv").scroll(function(){
　　var scrollTop = $(this).scrollTop();
	var scrollHeight = $(this)[0].scrollHeight; 
	var height = $(this).height();
　　if(scrollTop + height >= scrollHeight){
　　　　var p = ($(this).attr("data-page"))*1+1;
        loadzhanfaHistory(p,20);
        $(this).attr("data-page",p)
　　}
});

})
 
var iscanSend=0;
//检查发送框，obj为输入框id；type=1时代表是用户；cmd代表消息类型
function checkSend(obj,type,cmd){
    var iscon = $('#'+obj).val();
    if(iscon==""){
        alert("消息不能为空");
        return false;
    }
    if(type==1){
/*        if(iscanSend>0){
            alert("发送消息频率太快，请间隔15秒");
            return false;
        }*/
        if(iscon.length>200){
            alert("发送的内容不能超过200字");
            return false;
        }
        iscanSend=15;
        setTime();
    }
    else if(type=="teacher"){

    }
    if(cmd=="message"){
       sendMsg(iscon, 'text',type); 
    }
    else if(cmd=="note"){
    	if(type=="teacher"){

        }
        else{
        	if($("#teacherSelect").val()==""){
	            alert("请选择老师");
	            return;
	        }
	        
        }
        sendNote(iscon, 'text',type)

    }
       
}
function setTime() {
  iscanSend--
  if(iscanSend>0){
     setTimeout(function(){setTime()},1000);
  }
}
/*加载纸条历史*/
function loadHistoryNote(pages,lims){
    var lim = lims ? lims : 20;
    var page = pages ? pages : 1;
	var url = "?s=api/note/history/teacher_id";
    $.getJSON(url,{"room_id":room_id,"limit_num":lim,"page":page},function(response){
    	
            if(pages){
                if(parseInt(response.pageinfo.total) +1 == pages){
                    $("#note-msg").prepend('<div class="hostoryling"><span>没有更多聊天记录了</span></div>')    
                }
                if((response.pageinfo.total) >= pages){
                   noteHistoryPage(response.list) 
                }
                
            }
            else{
                for (var i = response.list.length-1; i >=0; i--) {
                    showNewNote(response.list[i]);

                }
            }
            //本人的消息删除回复按钮
            $(".replybt").each(function(){
                if($(this).attr("data-uid")==userinfo.user.id){
                    $(this).remove()
                }
            })					
	})
}
/*加载聊天历史*/
function loadHistoryMes(user_type,pages,lims){
    var typename= user_type == 2 ? "teacher" : "user"; 
    var lim = lims ? lims : 20;
    var page = pages ? pages : 1;
    var url = "?s=api/chat/history";
    $.getJSON(url,{"room_id":room_id,"limit_num":lim,"page":page,"user_type":user_type},function(response){
            if(pages){
                if(parseInt(response.pageinfo.total) +1 == pages){
                    if(typename == "teacher"){
                        $("#chat-teacher-messages").prepend('<div class="hostoryling"><span>没有更多聊天记录了</span></div>');
                    }
                    else{
                       $("#chat-messages").prepend('<div class="hostoryling"><span>没有更多聊天记录了</span></div>'); 
                    }
                    
                }
                if((response.pageinfo.total) >= pages){
                   historyPage(response.list,typename) 
                }
                
            }
            else{
                for (var i = response.list.length-1; i >=0; i--) {
                    showNewMsg(response.list[i],typename);

                }
            }
            //本人的消息删除回复按钮
            $(".replybt").each(function(){
                if($(this).attr("data-uid")==userinfo.user.id){
                    $(this).remove()
                }
            })                  
    })
}
/*获取用户信息*/
function getUserInfo(api,type){ 
    var url = api;
    $.getJSON(url,function(response){
        if(response){
         userinfo=  response;
         listenEvent();
         loadHistoryMes(2);
         loadHistoryMes(3);
         statusClass(response.room_status,type);
        }    
    })
    
}

/*获取老师列表*/
function getTeacherList(){ 
    var url = "?s=api/teacher/index";
    $.getJSON(url,function(response){
        if(response){
            var st = "<option value=''>请选择老师</option>"
            for(var i=0;i<response.length;i++){
                st+='<option value="'+response[i].id+'">'+response[i].user_nicename+'</option>'
            }
            $("#teacherSelect").html(st);
            $("#teacher-team").html(Handlebars.compile($("#teamTemplate").html())(response))
        }    
    })
    
}
/*加载喊单*/
function loadNowCall(){
    
    var url = "?s=api/call/now";
    $.getJSON(url,function(response){
        if(response){
         $("#callDataBox").html(Handlebars.compile($("#callTemplate").html())(response))  
        }    
    })
}
/*加载经济数据*/
function loadImportant(){
    var url = "?s=api/important/index";
    $.getJSON(url,function(response){
        if(response){
         $("#imDataBox").html(Handlebars.compile($("#importantTemplate").html())(response.imp));
         $(".yy-hd").attr("href",response.home[1])
         $(".yy-hd img").attr("src",response.home[0])
        }    
    })
}
/*加载喊单历史*/
function loadcallHistory(){
    var url = "?s=api/call/history";
    $.getJSON(url,function(response){
        if(response){
         $("#callHistoryDate").html(Handlebars.compile($("#callHistoryTemplate").html())(response.list))  
         $(".kai-tr:even").css("background-color","#eee");  
        }    
    })
}
/*加载投资战法*/
function loadzhanfaHistory(pages,limit_num){
    var url = "?s=api/zhanfa/index";
    var page = pages ? pages : 1;
    var data={page:page,limit_num:limit_num}
    $.getJSON(url,data,function(response){
        if(response){
        	if(pages){
                if(parseInt(response.pageinfo.total) +1 == pages){
                    $("#zf-box").append('<li class="hostoryling"><span>没有更多记录了</span></li>')    
                }
                if((response.pageinfo.total) >= pages){
                   $("#zf-box").append(Handlebars.compile($("#zhanFaTemplate").html())(response.list))
                }
                
            }
            else{
                $("#zf-box").html(Handlebars.compile($("#zhanFaTemplate").html())(response.list)) 
            }
          
        }    
    })
}
/*切换判断*/
function isTabLoad(obj,callback){
	var load = $(obj).attr("data-load");
	if(load==1){
		return;
	}
	callback();
	$(obj).attr("data-load",1);
}
function showPing(obj){
	$(obj).parent().parent().next(".ping-tr").slideToggle()
}
